﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Printing;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace RemotePrintTimer
{
    class Print
    {
        public OpmOutsourceProcessPage opData = null;
        //OutputMsg outMsg = new OutputMsg();
        NetApi api = new NetApi();
        int connectNetStatus = 0;
        JObject printConfig = null;
        List<JObject> list = new List<JObject>();
        public void orderprint(Action<String> callback)
        {
            //api.InitDomainConfig();
            //api.getUserInfo();
            connectNetStatus = 0;
            this.getOrderNoPrintParams(callback);            
            if (connectNetStatus == 1)
            {
                api.localLogin(new Action<String>((r) =>{ }));
            }
         }

        public void pringPage()
        {
            Dictionary<String,bool> pConfig = new Dictionary<string,bool>(){
                {"index",false},{"productCode",false},{"productName",false},{"drawingNo",false},{"description",false},{"processId_dictText",false},
                {"requirements",false},{"productVer",false},
                {"custCode",false},{"unitId_dictText",false},{"qty",false},{"weight",false},{"weightUnit_dictText",false},{"sizeLength",false},{"sizeWidth",false},{"widthUnit_dictText",false},
                {"area",false},
                {"areaUnit_dictText",false},{"unitPrice",false},
                {"amount",false},{"taxValue",false},{"taxAmount",false},{"requestDate",false},{"remark",false}
            };
            DataTable datas = new DataTable();
            GValues.list = list;
            list.ForEach(p => {
                if (p["field"].ToString().Equals("index"))
                {  pConfig["index"] = (bool) p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("序号");
                    }
                }
                if (p["field"].ToString().Equals("productCode"))
                {
                    pConfig["productCode"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("产品编码");

                    }
                }
                if (p["field"].ToString().Equals("productName"))
                {
                    pConfig["productName"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("产品名称");

                    }
                }
                if (p["field"].ToString().Equals("drawingNo"))
                {
                    pConfig["drawingNo"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("产品图号");

                    }
                }
                if (p["field"].ToString().Equals("description"))
                {
                    pConfig["description"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("产品描述");

                    }
                }
                if (p["field"].ToString().Equals("processId_dictText"))
                {
                    pConfig["processId_dictText"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("工序");

                    }
                }
                if (p["field"].ToString().Equals("requirements"))
                {
                    pConfig["requirements"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("加工要求");

                    }
                }
                if (p["field"].ToString().Equals("productVer"))
                {
                    pConfig["productVer"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("版本");

                    }
                }
                if (p["field"].ToString().Equals("custCode"))
                {
                    pConfig["custCode"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("客户料号");

                    }
                }
                if (p["field"].ToString().Equals("unitId_dictText"))
                {
                    pConfig["unitId_dictText"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("单位");

                    }
                }
                if (p["field"].ToString().Equals("qty"))
                {
                    pConfig["qty"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("数量");
                    }
                }
                if (p["field"].ToString().Equals("weight"))
                {
                    pConfig["weight"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        
                        datas.Columns.Add("重量");

                    }
                }
                if (p["field"].ToString().Equals("weightUnit_dictText"))
                {
                    pConfig["weightUnit_dictText"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {

                        datas.Columns.Add("重量单位");
                    }
                }
                if (p["field"].ToString().Equals("sizeLength"))
                {
                    pConfig["sizeLength"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("长");


                    }
                }
                if (p["field"].ToString().Equals("sizeWidth"))
                {
                    pConfig["sizeWidth"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("宽");

                    }
                }
                if (p["field"].ToString().Equals("widthUnit_dictText"))
                {
                    pConfig["widthUnit_dictText"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("长度单位");

                    }
                }
                if (p["field"].ToString().Equals("area"))
                {
                    pConfig["area"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("面积");

                    }
                }
                if (p["field"].ToString().Equals("areaUnit_dictText"))
                {
                    pConfig["areaUnit_dictText"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                       
                        datas.Columns.Add("面积单位");

                    }
                }
                if (p["field"].ToString().Equals("unitPrice"))
                {
                    pConfig["unitPrice"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {

                        datas.Columns.Add("单价");

                }
                if (p["field"].ToString().Equals("amount"))
                {
                    pConfig["amount"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("金额");

                    }
                    }
                }
                if (p["field"].ToString().Equals("taxValue"))
                {
                    pConfig["taxValue"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("税率");

                    }
                }
                if (p["field"].ToString().Equals("taxAmount"))
                {
                    pConfig["taxAmount"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("税额");

                    }
                }
                if (p["field"].ToString().Equals("requestDate"))
                {
                    pConfig["requestDate"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("需求日期");
                       
                    }
                }
                if (p["field"].ToString().Equals("remark"))
                {
                    pConfig["remark"] = (bool)p["status"];
                    if ((bool)p["status"])
                    {
                        datas.Columns.Add("备注");
                    }
                }
            });



            if (opData != null && opData.opmOutsourceProcessItemList != null)
            {
                int i = 0;
                foreach (OpmOutsourceProcessItemPage item in opData.opmOutsourceProcessItemList)
                {
                    i++;
                    DataRow row = datas.NewRow();
                    if (pConfig["index"])
                    {
                        row["序号"] = i;
                    }
                    if (pConfig["productCode"])
                    {
                        row["产品编码"] = item.productCode;
                    }
                    if (pConfig["productName"])
                    {
                        row["产品名称"] = item.productName;
                    }
                    if (pConfig["drawingNo"])
                    {
                        row["产品图号"] = item.drawingNo;
                    }
                    if (pConfig["description"])
                    {
                        row["产品描述"] = item.description;
                    }
                    if (pConfig["processId_dictText"])
                    {
                        row["工序"] = item.processId_dictText;
                    }
                    if (pConfig["requirements"])
                    {
                        row["加工要求"] = item.requirementDescs;
                    }
                    if (pConfig["productVer"])
                    {
                        row["版本"] = item.productVer;
                    }
                    if (pConfig["custCode"])
                    {
                        row["客户料号"] = item.custCode;
                    }
                    if (pConfig["unitId_dictText"])
                    {
                        row["单位"] = item.unitId_dictText;
                    }
                    if (pConfig["qty"])
                    {
                        row["数量"] = item.qty;
                    }

                    if (pConfig["sizeLength"])
                    {
                        row["长"] = item.sizeLength;
                    }
                    if (pConfig["sizeWidth"])
                    {
                        row["宽"] = item.sizeWidth;
                    }
                    if (pConfig["widthUnit_dictText"])
                    {
                        row["长度单位"] = item.widthUnit_dictText;
                    }
                    if (pConfig["area"])
                    {
                        row["面积"] = item.area;
                    }
                    if (pConfig["areaUnit_dictText"])
                    {
                        row["面积单位"] = item.areaUnit_dictText;
                    }
                    if (pConfig["weight"])
                    {
                        row["重量"] = item.weight;
                    }
                    if (pConfig["weightUnit_dictText"])
                    {
                        row["重量单位"] = item.weightUnit_dictText;
                    }
                    if (pConfig["unitPrice"])
                    {
                        row["单价"] = item.unitPrice;
                    }
                    if (pConfig["amount"])
                    {
                        row["金额"] = item.amount;

                    }
                    if (pConfig["taxValue"])
                    {
                        row["税率"] = item.taxValue;

                    }
                    if (pConfig["taxAmount"])
                    {
                        row["税额"] = item.taxAmount;

                    }
                    if (pConfig["requestDate"])
                    {
                        row["需求日期"] = item.requestDate;

                    }
                    if (pConfig["remark"])
                    {
                        row["备注"] = item.remark;

                    }
                    datas.Rows.Add(row);
                }
                //new PrintHelper().PrintPriview(datas, "外发单|单号：" + opData.outsourceNo, opData);
                LogHelper.WriteLog("开始打印！");
                new PrintHelper().Print(datas, "外发单|单号：" + opData.outsourceNo, opData);
            }
        }
        private void getOrderNoPrintParams(Action<String> callback)
        {
            Http.CreateHttpClient(GValues.tenant, GValues.token).GetAsync(GValues.domainLink + "bas/basUserPrintBuffer/list?username=" + GValues.account + "&printModule=xcxOutsourceNoParameter", new Action<Http.HttpResp>((r2) =>
            {
                var responCode = Convert.ToInt32(r2.Code);
                if (responCode == 200) //访问成功
                {
                    ResponResultC<JObject> cc = JsonConvert.DeserializeObject<ResponResultC<JObject>>(r2.AckStr());
                    if (cc.success)
                    {
                        try
                        {
                            if (cc.result["records"] != null && cc.result["records"].Count() > 0)
                            {
                                for (int i = 0; i < cc.result["records"].Count(); i++)
                                {
                                    String bb = JsonConvert.SerializeObject(cc.result["records"][i]);
                                    JObject aa = (JObject)JsonConvert.DeserializeObject(bb);
                                    String id = aa["id"].ToString();
                                    JArray ee = (JArray)JsonConvert.DeserializeObject(aa["printParameter"].ToString());
                                    JObject printOrderNo = (JObject)JsonConvert.DeserializeObject(ee[0].ToString());
                                    string outSourceNo = (string)printOrderNo["outsourceNo"];
                                    if (outSourceNo == "")
                                    {
                                        LogHelper.WriteLog("没有打印数据！");
                                    }
                                    else
                                    {
                                        getPrintParams(outSourceNo);
                                        callback(outSourceNo);
                                        //getOpDatalist(outSourceNo); 20241025 获取到打印配置，在获取数据
                                        cancelPrintData(id);
                                        LogHelper.WriteLog("获取打印数据成功！");
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            LogHelper.WriteLog("数据转换失败！" + e.Message, null);
                        }
                    }
                    else
                    {
                        LogHelper.WriteLog("获取数据失败！" + cc.message, null);
                    }
                }
                else
                {
                    LogHelper.WriteLog("网络连接失败！" + r2.Error, null);
                }
            }));
        }
        private String cancelPrintData(String id)
        {

            //var obj = new Dictionary<String,String>{ {"outsourceNo",""}};
            //String[] bb = new String[] { JsonConvert.SerializeObject(obj)};
            //var aa  = new Dictionary<String,String> {
            //        {"code","0"},
            //        {"name","0"},
            //        {"username",GValues.account},
            //        {"printModule","xcxOutsourceNoParameter"},
            //        {"printParameter",JsonConvert.SerializeObject(bb)}
            //    };
            String res = "false";
            try
            {
                //string postData = JsonConvert.SerializeObject(aa);
                Http.CreateHttpClient(GValues.tenant, GValues.token).DeleteAsync(GValues.domainLink + "bas/basUserPrintBuffer/delete?id=" + id, new Action<Http.HttpResp>((r) =>         
                //Http.CreateHttpClient(GValues.domainLink + "bas/basUserPrintBuffer/add", GValues.tenant, GValues.token).PostAsync(postData, new Action<Http.HttpResp>((r) =>
                {
                    var responCode = Convert.ToInt32(r.Code);
                    if (responCode == 200) //访问成功
                    {
                        res = "ok";
                    }
                    else
                    {
                        LogHelper.WriteLog("回写打印数据失败！" + r.Code + " " + " " + responCode + " " + r.Error);

                    }
                }));

            }
            catch (System.Exception err)
            {
                LogHelper.WriteLog("回写打印数据失败！" + err.Message);
            }
            return res;
        }
        private void getPrintParams(String outSourceNo)
        {
            Http.CreateHttpClient(GValues.tenant, GValues.token).GetAsync(GValues.domainLink + "bas/basUserPrintBuffer/list?username=systemPrinter&printModule=OpmOutsourceProcessPrint", new Action<Http.HttpResp>((r2) =>
            {
                var responCode = Convert.ToInt32(r2.Code);
                if (responCode == 200) //访问成功
                {
                    ResponResultC<JObject> cc = JsonConvert.DeserializeObject<ResponResultC<JObject>>(r2.AckStr());
                    if (cc.success)
                    {
                        try
                        {
                            String bb = JsonConvert.SerializeObject(cc.result["records"][0]);
                            JObject aa = (JObject) JsonConvert.DeserializeObject(bb);
                            JArray ee = (JArray)JsonConvert.DeserializeObject(aa["printParameter"].ToString());
                            printConfig = (JObject)JsonConvert.DeserializeObject(ee[0].ToString());
                            string jsonString = printConfig["tableCols"].ToString();
                            list = JsonConvert.DeserializeObject<List<JObject>>(jsonString);

                            getOpDatalist(outSourceNo); //20241025 获取到打印配置，在获取数据
                            LogHelper.WriteLog("获取打印配置成功！");
                        }
                        catch (Exception e)
                        {
                            LogHelper.WriteLog("数据转换失败！" + e.Message,null);
                        }
                    }
                    else
                    {
                        LogHelper.WriteLog("获取数据失败！" + cc.message,null);
                    }
                }
                else
                {
                    LogHelper.WriteLog("网络连接失败！" + r2.Error,null);
                }
            }));
        }
        private OpmOutsourceProcessPage getOpDatabyId(String id) {
            OpmOutsourceProcessPage opm = new OpmOutsourceProcessPage();
            //string outsourceNo = "W-20240424-012";
            //获取到了token
            Http.CreateHttpClient(GValues.tenant, GValues.token).GetAsync(GValues.domainLink + "opm/opmOutsourceProcess/queryOpmOutsourceProcessItemByMainId?id=" + id, new Action<Http.HttpResp>((r2) =>
            {
                var responCode = Convert.ToInt32(r2.Code);
                if (responCode == 200) //访问成功
                {
                    ResponResultB<OpmOutsourceProcessItemPage> cc = JsonConvert.DeserializeObject<ResponResultB<OpmOutsourceProcessItemPage>>(r2.AckStr());
                    if (cc.success)
                    {
                        try
                        {
                            BindingList<OpmOutsourceProcessItemPage> list = cc.result;
                            List<OpmOutsourceProcessItemPage> list1 = list.ToList();
                            list1 = list1.OrderBy(p => p.sequence).ToList();
                            BindingList<OpmOutsourceProcessItemPage> list2 = new BindingList<OpmOutsourceProcessItemPage>(list1);
                            opData.opmOutsourceProcessItemList = list2;
                            pringPage();
                            LogHelper.WriteLog("数据获取成功！");
                        }
                        catch (Exception e)
                        {
                            LogHelper.WriteLog("数据转换失败！" + e.Message,null);

                        }
                    }
                    else
                    {
                        LogHelper.WriteLog("获取数据失败！" + cc.message,null);
                    }
                }
                else
                {
                    LogHelper.WriteLog("网络连接失败！" + r2.Error,null);
                }
            }));

            return opm;
        }

        private OpmOutsourceProcessPage getOpDatalist(String outSourceNo)
        {
            OpmOutsourceProcessPage opm = new OpmOutsourceProcessPage();
            connectNetStatus = 1;
            //获取到了token
            Http.CreateHttpClient(GValues.tenant, GValues.token).GetAsync(GValues.domainLink + "opm/opmOutsourceProcess/confirmAndPrint?outSourceNo=" + outSourceNo, new Action<Http.HttpResp>((r2) =>
            {
                var responCode = Convert.ToInt32(r2.Code);
                if (responCode == 200) //访问成功
                {
                    ResponResult<OpmOutsourceProcessPage> cc = JsonConvert.DeserializeObject<ResponResult<OpmOutsourceProcessPage>>(r2.AckStr());
                    if (cc.success)
                    {
                        connectNetStatus = 0;
                        try
                        {
                            opData = cc.result;
                            opData.supplierId_dictText = opData.supplier.shortName;
                            getOpDatabyId(opData.id);
                            LogHelper.WriteLog("数据获取成功！");

                        }
                        catch (Exception e)
                        {
                            LogHelper.WriteLog("数据转换失败！" + e.Message,null);
                        }
                    }
                    else
                    {
                        LogHelper.WriteLog("获取数据失败！" + cc.message,null);
                    }
                }
                else
                {
                    LogHelper.WriteLog("网络连接失败！" + r2.Error,null);
                }
            }));

            return opm;
        }
    }
}
